#! /bin/bash
#set -x
MISC_PATH=misc
AP_PATH=ap
MP_PATH=mp
OUT_PATH=package
UPDATE_SCRIPT="META-INF/com/google/android/updater-script"

ALL_AP_FILES="boot.img system.img"
ALL_MP_FILES="amss.mbn amsshd.mbn oemsblhd.mbn oemsbl.mbn qcsbl.mbn qcsblhd_cfgdata.mbn"

#Create the directory structure
if [ ! -d ${OUT_PATH}/system ]; then
mkdir -p ${OUT_PATH}/system
fi

if [ "$IS_EMMC" = "y" -o "$IS_EMMC" = "Y" ];then
PREFIX="emmc_"
else
PREFIX=""
fi

#Test if all the files needed exist.
for i in `echo $ALL_AP_FILES`; do ALL_FILES=${AP_PATH}/${i}\ ${ALL_FILES};done
for i in `echo $ALL_MP_FILES`; do ALL_FILES=${MP_PATH}/${i}\ ${ALL_FILES};done
echo ${ALL_FILES}

for i in `echo ${ALL_FILES}`; do if [ ! -f $i ];then echo "Can not find \"$i\"";exit 1;fi;done

if [ ! -d $OUT_PATH ];then
mkdir $OUT_PATH
fi

#Rename all the mp files and lk image
echo ${OUT_PATH}
cat ${MP_PATH}/qcsblhd_cfgdata.mbn > ${OUT_PATH}/QCSBLHD.enc
cat ${MP_PATH}/qcsbl.mbn > ${OUT_PATH}/QCSBL.enc
cat ${MP_PATH}/oemsblhd.mbn > ${OUT_PATH}/OEMSBL.enc; cat ${MP_PATH}/oemsbl.mbn >> ${OUT_PATH}/OEMSBL.enc
cat ${MP_PATH}/amsshd.mbn > ${OUT_PATH}/AMSS.enc; cat ${MP_PATH}/amss.mbn >> ${OUT_PATH}/AMSS.enc

cat ${AP_PATH}/${IS_EMMC}appsboothd.mbn > ${OUT_PATH}/APPSBOOT.enc; cat ${AP_PATH}/${IS_EMMC}appsboot.mbn >> ${OUT_PATH}/APPSBOOT.enc

#TODO Hard coded!!!!! Need to check the build version
echo "UDNCKOLG" > ${OUT_PATH}/build_version.enc

#Copy the META_INF files to $OUT_PATH
cp -arf ${MISC_PATH}/META-INF ${OUT_PATH}

#Copy recovery files to $OUT_PATH
#TODO NEED TO CHANGE TO EXTRACT FROM recovery.img
cp -arf ${MISC_PATH}/recovery ${OUT_PATH}

#Copy boot.img to $OUT_PATH
cp -arf ${AP_PATH}/boot.img ${OUT_PATH}

#Extract files from image
echo "Extracting system.img"
cd ${OUT_PATH}/system
../../${MISC_PATH}/unyaffs ../../${AP_PATH}/system.img 
cd -

#Modify the updater-script. Replace with the new sha1sum of /system/lib files
echo "Setup updater-script"
str=""; for i in `find ${OUT_PATH}/system/lib `;do if [ -f $i ]; then str=${str}\\\"${i}\\\"\,\ \\\"`sha1sum $i | cut -f 1 -d ' '`\\\",\ ;fi;done
str=`echo $str | sed 's/\(.*\),/\1/g'`
sed -i  "s%\(retouch_binaries(\)\(.*\)\()\)%\1${str}\3%g" ${OUT_PATH}/${UPDATE_SCRIPT}

#Zip the package
echo "Zip the package"
cd ${OUT_PATH}
zip -qyr ../raw.zip .
cd -

#Sign the package
echo "Signing the package"
java -Xmx2048m -jar ${MISC_PATH}/signapk.jar -w ${MISC_PATH}/testkey.x509.pem ${MISC_PATH}/testkey.pk8 raw.zip signed_`date '+%y%m%d_%H%M%S'`.zip

#Remove temp files
echo "Removing temp files"
rm $OUT_PATH -Rf
rm raw.zip -f

exit 0


